//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.apexedu.identity.action;

import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.SpringUtils;
import com.apexedu.framework.util.SysPropertiesUtil;
import com.apexedu.identity.entity.LoginUserVO;
import com.apexedu.identity.entity.TSysButton;
import com.apexedu.identity.entity.TSysDepart;
import com.apexedu.identity.entity.TSysMenu;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.identity.security.CasLoginUtil;
import com.apexedu.identity.service.IdUserService;
import com.apexedu.identity.service.LoginCustom;
import com.apexedu.identity.service.LogoutCustom;
import com.apexedu.identity.util.PolymorphismMD5;
import com.apexedu.support.cache.CacheUtils;
import com.apexedu.support.spring.SpringUtil;
import com.apexedu.sys.action.AbstractBaseActionSupport;
import com.apexedu.sys.uniid.server.UniIdServiceImpl;
import com.apexedu.sys.util.BusinessLogUtil;
import com.apexedu.sys.util.SystemSelfCheck;
import com.apexedu.util.CookieUtil;
import com.apexedu.util.DateUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.crypto.DigestUtil;
import com.apexedu.util.json.JsonUtil;
import com.opensymphony.xwork2.ActionContext;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("idLoginAction")
@Scope("prototype")
public class IdLoginAction extends AbstractBaseActionSupport {
    private static final Log LOG = LogFactory.getLog(IdLoginAction.class);
    private static final int COOKIE_MAX_AGE = 1209600;
    private HttpServletResponse response = null;
    private TSysUser tsysUser;
    @Resource(
            name = "idUserService"
    )
    private IdUserService idUserService;
    private List<TSysMenu> tsysMenues;
    private List<TSysButton> tsysMenueButtons;
    private static boolean Valid = false;

    static {
        Valid = SystemSelfCheck.isValidate();
    }

    public IdLoginAction() {
    }

    public String execute() {
        HttpServletRequest request = this.getRequest();
        HttpSession session = request.getSession();
        if(session.getAttribute("ys_LoginUser") != null) {
            if(StringUtil.isNotBlank(request.getParameter("returnURL"))) {
                this.setParameter("returnURL", request.getParameter("returnURL"));
                return "redirect";
            } else {
                return "success";
            }
        } else {
            if(isSsoEnabled()) {
                String userLoginId = request.getRemoteUser();
                if(StringUtil.isNotBlank(userLoginId)) {
                    loginByServerSide(userLoginId, request);
                    return "success";
                }
            }

            if(!Valid) {
                for(int k = 0; k < 50; ++k) {
                    LOG.fatal(SystemSelfCheck.getMessage());
                }
            }

            this.setParameter("returnURL", request.getParameter("returnURL"));
            return "login";
        }
    }

    public String loginProcess(boolean browserLogin) {
        if(this.tsysUser != null && this.tsysUser.getUserloginid() != null) {
            HttpServletRequest request = this.getRequest();
            if(browserLogin && ActionContext.getContext() != null) {
                this.setParameter("returnURL", request.getParameter("returnURL"));
            }

            HttpSession session = request.getSession(true);
            if(SysPropertiesUtil.getBoolean("open_U_V_I_C") && browserLogin) {
                String u_v_i_c = request.getParameter("u_v_i_c");
                if(StringUtil.isBlank(u_v_i_c)) {
                    return "请输入验证码！";
                }

                String v_i_c = (String)session.getAttribute("ys_image4login_rand");
                if(!u_v_i_c.equals(v_i_c)) {
                    return "您输入的验证码错误！";
                }
            }

            TSysUser userInDB = this.idUserService.entity(this.tsysUser.getUserloginid());
            if(userInDB == null) {
                return "用户名或密码不正确！";
            } else {
                TSysUser userInSession = (TSysUser)session.getAttribute("ys_LoginUser");
                if(userInSession != null) {
                    return userInSession.getUserloginid().equals(this.tsysUser.getUserloginid())?"success":"本地已有其他账户登录，如需切换用户请先退出登陆！";
                } else {
                    Cookie cookie_loginID = CookieUtil.getCookie("UHsTwUjda12jLk3", request);
                    Cookie cookie_authcode = CookieUtil.getCookie("AaFdwUjdJG2ilR9", request);
                    String userLoginId;
                    String departState;
                    if(cookie_loginID != null && cookie_authcode != null) {
                        String cookieLoginID = cookie_loginID.getValue();
                        departState = cookie_authcode.getValue();
                        if(StringUtil.isBlank(cookieLoginID) || StringUtil.isBlank(departState)) {
                            return "登录校验信息不正确！";
                        }

                        userLoginId = userInDB.getUserloginid() + userInDB.getUserpwd() + "ys123";
                        userLoginId = PolymorphismMD5.hash(userLoginId);
                        if(!departState.equals(userLoginId)) {
                            return "登录校验信息不正确！";
                        }
                    } else {
                        LoginCustom loginCustom = (LoginCustom)SpringUtil.getBeanByType(LoginCustom.class);
                        if(loginCustom != null) {
                            boolean loginSuccess = loginCustom.login(this.tsysUser.getUserloginid(), this.tsysUser.getUserpwd(), getIpAddr(request), request);
                            if(!loginSuccess) {
                                userLoginId = (String)request.getAttribute("CustomMessage");
                                if(StringUtil.isBlank(userLoginId)) {
                                    userLoginId = "用户名或密码错误！";
                                }

                                return userLoginId;
                            }
                        } else {
                            departState = (String)session.getAttribute("uuuid");
                            if(StringUtil.isBlank(departState)) {
                                if(browserLogin && SysPropertiesUtil.getBoolean("SWITCH_PASSWORD_MD5")) {
                                    userLoginId = PolymorphismMD5.hash(this.tsysUser.getUserpwd()).toUpperCase();
                                } else {
                                    userLoginId = this.tsysUser.getUserpwd();
                                }

                                if(browserLogin && !userInDB.getUserpwd().equals(userLoginId)) {
                                    return "用户名或密码错误！";
                                }
                            } else if(browserLogin && SysPropertiesUtil.getBoolean("SWITCH_PASSWORD_MD5")) {
                                if(!DigestUtil.isMatchByLivebosMD5(this.tsysUser.getUserpwd(), departState, userInDB.getUserpwd())) {
                                    return "用户名或密码错误！";
                                }
                            } else {
                                userLoginId = this.tsysUser.getUserpwd();
                                if(browserLogin && !DigestUtil.getHmacMd5Str(departState, userInDB.getUserpwd()).equals(userLoginId)) {
                                    return "用户名或密码错误！";
                                }
                            }
                        }
                    }

                    if("-1".equals(userInDB.getState())) {
                        return "该帐号未激活，请登录注册邮箱点击激活链接！";
                    } else if("-2".equals(userInDB.getState())) {
                        return "您的信息正在审核中，暂不能登录！";
                    } else if("0".equals(userInDB.getState())) {
                        return "该用户帐号暂停使用！";
                    } else if("-3".equals(userInDB.getState())) {
                        return "您的信息正在审核中，暂不能登录！";
                    } else {
                        TSysDepart depart = userInDB.getDepart();
                        if(depart == null && !idUserService.USER_STATE_BASE.equals(userInDB.getState())) {
                            return "该用户没有隶属单位信息！";
                        } else {
                            if(depart != null){
                                departState = depart.getState();
                                if("0".equals(departState)) {
                                    return "该用户的单位已经被注销或暂停使用！";
                                }
                            }
                            userLoginId = userInDB.getUserloginid();
                            boolean singleLogin = SysPropertiesUtil.getBoolean("singleLogin");
                            if(singleLogin) {
                                String NO_SINGLE_LOGIN_USERTYPE = SysPropertiesUtil.get("noSingleLogin.userType");
                                String userType = userInDB.getUsertype();
                                if(StringUtil.isBlank(userType) || StringUtil.isBlank(NO_SINGLE_LOGIN_USERTYPE) || !userType.equals(NO_SINGLE_LOGIN_USERTYPE)) {
                                    HttpSession exsit_session = LoginUserVO.getThisUserSession(userLoginId);
                                    if(exsit_session != null && session != exsit_session) {
                                        if(LOG.isInfoEnabled()) {
                                            LOG.info("一个已经登录的账户强行登录系统！");
                                        }

                                        exsit_session.invalidate();
                                    }
                                }
                            }

                            int maxOnlineCount = SysPropertiesUtil.getInteger("maxOnlineCount");
                            if(maxOnlineCount < 1) {
                                LOG.error("没有取到最大在线人数值，将使用默认最大人数1000！");
                                maxOnlineCount = 1000;
                            }

                            if(LoginUserVO.getCurrentOnlineCount() >= maxOnlineCount) {
                                if(LOG.isWarnEnabled()) {
                                    LOG.warn("此服务器在线人数已达到最大数：" + maxOnlineCount);
                                }

                                return "此服务器在线人数已达到最大数，请稍候再登录系统！";
                            } else {
                                LoginUserVO loginUserVO = new LoginUserVO();
                                loginUserVO.setDepart(userInDB.getDepart());
                                loginUserVO.setState(userInDB.getState());
                                loginUserVO.setUserid(userInDB.getUserid());
                                loginUserVO.setUserloginid(userInDB.getUserloginid());
                                loginUserVO.setUsername(userInDB.getUsername());
                                loginUserVO.setUsertype(userInDB.getUsertype());
                                loginUserVO.setLastloginip(userInDB.getLastloginip());
                                loginUserVO.setLastlogintime(userInDB.getLastlogintime());
                                loginUserVO.setLogintimes(userInDB.getLogintimes());
                                loginUserVO.setClientIP(getIpAddr(request));

                                try {
                                    loginUserVO.setServerIP(InetAddress.getLocalHost().getHostAddress());
                                } catch (UnknownHostException var18) {
                                    LOG.error(var18);
                                    return "获取登录服务节点地址出错：" + var18.getMessage();
                                }

                                loginUserVO.setLoginTime(new Date());
                                loginUserVO.setSession(session);
                                session.setAttribute("ys_LoginUser", loginUserVO);
                                String rememberMe = request.getParameter("remUser");
                                if(browserLogin && rememberMe != null && rememberMe.endsWith("true")) {
                                    String cookieValue = userInDB.getUserloginid() + userInDB.getUserpwd() + "ys123";
                                    cookieValue = PolymorphismMD5.hash(cookieValue);
                                    cookie_authcode = new Cookie("AaFdwUjdJG2ilR9", cookieValue);
                                    cookie_authcode.setMaxAge(1209600);
                                    cookie_authcode.setPath("/");
                                    this.getResponse().addCookie(cookie_authcode);

                                    try {
                                        this.tsysUser.setUserloginid(URLEncoder.encode(userInDB.getUserloginid(), "utf-8"));
                                    } catch (UnsupportedEncodingException var17) {
                                        LOG.error(var17);
                                    }

                                    cookie_loginID = new Cookie("UHsTwUjda12jLk3", this.tsysUser.getUserloginid());
                                    cookie_loginID.setMaxAge(1209600);
                                    cookie_loginID.setPath("/");
                                    this.getResponse().addCookie(cookie_loginID);
                                }

                                this.tsysMenues = this.idUserService.loadMyMenu(loginUserVO);
                                session.setAttribute("ys_MyRightMenues", this.tsysMenues);
                                return "success";
                            }
                        }
                    }
                }
            }
        } else {
            return "参数不正确！";
        }
    }

    public void ajaxlogin() {
        String act = this.getRequest().getParameter("act");
        Map<String, Object> outData = new HashMap();
        HttpSession session = this.getSession();
        String userLoginId;
        if("login".equals(act)) {
            userLoginId = "errorTimes_" + getIpAddr(this.getRequest());
            int maxLoginErrorTimes = 5;
            Integer errorTimes = (Integer)CacheUtils.get(userLoginId);
            if(errorTimes != null && errorTimes.intValue() > maxLoginErrorTimes) {
                outData.put("msg", "错误次数太多！请1小时后再尝试登录。");
            } else {
                String mesg = this.loginProcess(true);
                outData.put("msg", mesg);
                if("success".equals(mesg)) {
                    LoginUserVO loginuser = (LoginUserVO)session.getAttribute("ys_LoginUser");
                    outData.put("usertype", loginuser.getUsertype());
                    outData.put("userdepart", loginuser.getDepart().getDepartname());
                    outData.put("userdepartid", loginuser.getDepart().getDepartid());
                    outData.put("lastloginip", loginuser.getLastloginip());
                    String lastlogintime = loginuser.getLastlogintime() == null?"":DateUtil.formatDate(loginuser.getLastlogintime());
                    outData.put("lastlogintime", lastlogintime);
                    BusinessLogUtil.log(loginuser.getUserloginid(), "TSysUser", 4, loginuser.getClientIP(), "登录成功");
                } else {
                    BusinessLogUtil.log(this.tsysUser.getUserloginid(), "TSysUser", 4, getIpAddr(this.getRequest()), "登录失败：" + mesg);
                    if(errorTimes == null) {
                        errorTimes = Integer.valueOf(1);
                    } else {
                        errorTimes = Integer.valueOf(errorTimes.intValue() + 1);
                        if(errorTimes.intValue() > 2) {
                            outData.put("msg", mesg + "<br/><br/>再出错 " + (maxLoginErrorTimes - errorTimes.intValue() + 1) + " 次，系统将锁定！");
                        }
                    }

                    CacheUtils.put(userLoginId, errorTimes);
                }
            }
        } else if("logout".equals(act)) {
            this.logout();
            outData.put("msg", "success");
        } else if("checklogin".equals(act)) {
            TSysUser loginuser = (TSysUser)session.getAttribute("ys_LoginUser");
            if(loginuser == null) {
                outData.put("msg", "no");
            } else {
                outData.put("msg", "ok");
                outData.put("usertype", loginuser.getUsertype());
                outData.put("userdepart", loginuser.getDepart().getDepartname());
                outData.put("userdepartid", loginuser.getDepart().getDepartid());
                outData.put("lastloginip", loginuser.getLastloginip());
                String lastlogintime = loginuser.getLastlogintime() == null?"":DateUtil.formatDate(loginuser.getLastlogintime());
                outData.put("lastlogintime", lastlogintime);
            }
        } else if("checkUserInSession".equals(act)) {
            userLoginId = this.getRequest().getParameter("userLoginId");
            Boolean isLogined = Boolean.valueOf(false);
            if(StringUtil.isNotBlank(userLoginId)) {
                userLoginId = DBUtil.queryField("select userloginid from t_sys_user where username=? or userloginid=?", new Object[]{userLoginId, userLoginId});
                isLogined = Boolean.valueOf(UniIdServiceImpl.isThisUserAlreadyLogined(userLoginId));
            }

            outData.put("msg", isLogined.toString());
        }

        try {
            userLoginId = JsonUtil.getJSONString(outData);
        } catch (JSONException var10) {
            userLoginId = "{msg:'json对象转换异常：" + var10 + "'}";
        }

        this.putResultStringToView(userLoginId);
    }

    public String login() {
        String mesg = this.loginProcess(true);
        if("success".equals(mesg)) {
            BusinessLogUtil.log(this.tsysUser.getUserloginid(), "TSysUser", 4, getIpAddr(this.getRequest()), "登录成功");
            return "success";
        } else {
            if(this.tsysUser != null) {
                BusinessLogUtil.log(this.tsysUser.getUserloginid(), "TSysUser", 4, getIpAddr(this.getRequest()), "登录失败：" + mesg);
            }

            this.addActionMessage(mesg);
            return "login";
        }
    }

    public static void loginByServerSide(String userLoginId, HttpServletRequest request) {
        if(StringUtil.isNotBlank(userLoginId)) {
            TSysUser user = (TSysUser)DBUtil.queryBean("select * from t_sys_user where userloginid=?", TSysUser.class, new Object[]{userLoginId});
            if(user == null) {
                IdUserService service = SpringUtil.getBean("idUserService");
                user = service.getRemoteUser(userLoginId);
                if(user == null){
                    String mes = "本系统中未查找到[" + userLoginId + "]用户的信息！";
                    LOG.error(mes);
                    throw new RuntimeException(mes);
                }
                }

            IdLoginAction idLoginAction = (IdLoginAction)SpringUtil.getBean("idLoginAction");
            idLoginAction.setServletRequest(request);
            idLoginAction.setTsysUser(user);
            String ss = idLoginAction.loginProcess(false);
            if(LOG.isInfoEnabled()) {
                LOG.info("从CAS执行登录本地应用" + user.getUserloginid() + "[" + user.getUsername() + "]");
            }

            if(!ss.equals("success")) {
                LOG.error("出现错误：无法加载此用户在本地的信息！" + user.getUserloginid() + "[" + user.getUsername() + "]");
                LOG.error(ss);
                throw new RuntimeException("出现错误：无法加载此用户在本地的信息！" + user.getUserloginid() + "[" + user.getUsername() + "]");
            }
        }

    }

    public static final boolean isSsoEnabled() {
        return CasLoginUtil.isSsoEnabled();
    }

    public final String logout() {
        SystemSelfCheck.validate();
        CookieUtil.removeCookie("AaFdwUjdJG2ilR9", this.getRequest(), this.getResponse());
        CookieUtil.removeCookie("UHsTwUjda12jLk3", this.getRequest(), this.getResponse());
        this.getSession().invalidate();
        LogoutCustom logoutCustom = (LogoutCustom)SpringUtils.getBeanByType(LogoutCustom.class);
        if(logoutCustom != null) {
            logoutCustom.logout(this.getRequest(), this.getResponse());
        }

        return "login";
    }

    public String leftMenu() {
        HttpSession session = this.getRequest().getSession();
        return session != null && session.getAttribute("ys_LoginUser") != null?"leftMenu":"login";
    }

    public String headMessage() {
        HttpSession session = this.getRequest().getSession();
        return session != null && session.getAttribute("ys_LoginUser") != null?"headMessage":"login";
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public TSysUser getTsysUser() {
        return this.tsysUser;
    }

    public void setTsysUser(TSysUser tsysUser) {
        this.tsysUser = tsysUser;
    }

    public List<TSysMenu> getTsysMenues() {
        return this.tsysMenues;
    }

    public void setTsysMenues(List<TSysMenu> tsysMenues) {
        this.tsysMenues = tsysMenues;
    }

    public List<TSysButton> getTsysMenueButtons() {
        return this.tsysMenueButtons;
    }

    public void setTsysMenueButtons(List<TSysButton> tsysMenueButtons) {
        this.tsysMenueButtons = tsysMenueButtons;
    }

    public HttpServletResponse getResponse() {
        if(this.response == null) {
            this.response = ServletActionContext.getResponse();
        }

        return this.response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }
}
